<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-input-wrapper">
				<text class="search-icon">🔍</text>
				<input class="search-input" v-model="searchKeyword" placeholder="搜索备忘录内容..." 
					placeholder-style="color: #999" @input="onSearchInput" />
				<text class="clear-icon" v-if="searchKeyword" @tap="clearSearch">✕</text>
			</view>
			
			<!-- 过滤标签 -->
			<view class="filter-tag" v-if="filterType !== 'all'">
				<text class="filter-text">{{ filterType === 'pending' ? '待完成' : '已完成' }}</text>
				<text class="filter-clear" @tap="clearFilter">✕</text>
			</view>
		</view>

		<!-- 备忘录列表 -->
		<view class="memo-list" v-if="sortedMemos.length > 0">
			<view class="memo-item" v-for="(memo, index) in sortedMemos" :key="index">
				<view class="memo-header">
					<view class="header-left">
						<text class="memo-time">{{ formatTime(memo.remindTime) }}</text>
						<view class="priority-badge" :class="'priority-' + memo.priority">
							<text class="badge-text">{{ getPriorityText(memo.priority) }}</text>
						</view>
					</view>
					<view class="memo-actions">
						<text class="action-btn detail" @tap="showDetail(memo.originalIndex)">详情</text>
						<text class="action-btn complete" v-if="!memo.completed"
							@tap="completeMemo(memo.originalIndex)">完成</text>
						<text class="status-badge" v-else>已完成</text>
						<text class="action-btn edit" @tap="editMemo(memo.originalIndex)">编辑</text>
						<text class="action-btn delete" @tap="deleteMemo(memo.originalIndex)">删除</text>
					</view>
				</view>
				<view class="memo-content-wrapper">
					<text class="memo-content-text">{{ getTruncatedContent(memo.content) }}</text>
				</view>
				<view class="memo-status">
					<text class="status-text" v-if="memo.completed">已完成</text>
					<text class="status-text pending" v-else>待完成</text>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<text class="empty-text">暂无备忘录</text>
		</view>

		<!-- 编辑模态框 -->
		<view class="modal" v-if="showEditModal" @tap="closeEditModal">
			<view class="modal-content" @tap.stop>
				<textarea class="modal-input" v-model="editContent" placeholder-style="color: #999"
					placeholder="输入HTML或纯文本内容...">
			</textarea> <!-- 优先级选择 -->
				<view class="priority-section">
					<view class="priority-tabs">
						<view class="priority-tab" :class="{ active: editPriority === 'low' }"
							@tap="editPriority = 'low'">
							<text class="priority-text">低</text>
						</view>
						<view class="priority-tab" :class="{ active: editPriority === 'medium' }"
							@tap="editPriority = 'medium'">
							<text class="priority-text">中</text>
						</view>
						<view class="priority-tab" :class="{ active: editPriority === 'high' }"
							@tap="editPriority = 'high'">
							<text class="priority-text">高</text>
						</view>
					</view>
				</view>

				<!-- 编辑时间选择 -->
				<view class="time-picker-group">
					<text class="time-label">创建时间:</text>
					<uni-datetime-picker v-model="editDateTime" type="datetime" :clearIcon="false" placeholder="选择日期时间">
					</uni-datetime-picker>
				</view>

				<view class="modal-buttons">
					<button class="btn btn-primary" @tap="saveEdit">保存</button>
					<button class="btn btn-secondary" @tap="closeEditModal">取消</button>
				</view>
			</view>
		</view>

		<!-- 详情模态框 -->
		<view class="modal" v-if="showDetailModal" @tap="closeDetailModal">
			<view class="modal-content detail-modal" @tap.stop>
				<view class="detail-header">
					<text class="detail-title">备忘录详情</text>
					<text class="close-btn" @tap="closeDetailModal">✕</text>
				</view>
				<view class="detail-body">
					<view class="detail-info">
						<text class="detail-label">创建时间：</text>
						<text class="detail-value">{{ formatTime(detailMemo.remindTime) }}</text>
					</view>
					<view class="detail-info">
						<text class="detail-label">优先级：</text>
						<text class="detail-value">{{ getPriorityText(detailMemo.priority) }}</text>
					</view>
					<view class="detail-info">
						<text class="detail-label">状态：</text>
						<text class="detail-value">{{ detailMemo.completed ? '已完成' : '待完成' }}</text>
					</view>
					<view class="detail-content-section">
						<text class="detail-label">内容：</text>
						<mp-html :content="detailMemo.content" class="detail-content"></mp-html>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import mpHtml from '@/uni_modules/mp-html/components/mp-html/mp-html.vue';
import { memoAPI } from '@/utils/api.js';

export default {
	components: {
		mpHtml
	},
	data() {
		return {
			memos: [],
			searchKeyword: '',
			filterType: 'all', // 过滤类型: all, pending, completed
			showEditModal: false,
			showDetailModal: false,
			detailMemo: {},
			editingIndex: -1,
			editMemoId: null,
			editContent: '',
			editDateTime: '',
			editPriority: 'medium',
			storageKey: 'memoList'
		}
	},
	computed: {
		// 排序后的备忘录列表
		sortedMemos() {
			const priorityOrder = { high: 3, medium: 2, low: 1 };

			// 先过滤搜索关键词
			let filteredMemos = this.memos;
			if (this.searchKeyword.trim()) {
				const keyword = this.searchKeyword.trim().toLowerCase();
				filteredMemos = this.memos.filter(memo => {
					// 搜索内容（去除HTML标签）
					const plainContent = memo.content.replace(/<[^>]*>/g, '').toLowerCase();
					return plainContent.includes(keyword);
				});
			}
			
			// 根据过滤类型过滤
			if (this.filterType === 'pending') {
				filteredMemos = filteredMemos.filter(memo => !memo.completed);
			} else if (this.filterType === 'completed') {
				filteredMemos = filteredMemos.filter(memo => memo.completed);
			}

			return filteredMemos.map((memo, index) => ({
				...memo,
				originalIndex: this.memos.indexOf(memo) // 保持原始索引
			})).sort((a, b) => {
				// 第一优先级：未完成排在前面
				if (a.completed !== b.completed) {
					return a.completed ? 1 : -1;
				}

				// 第二优先级：优先级高的排在前面
				const priorityDiff = priorityOrder[b.priority] - priorityOrder[a.priority];
				if (priorityDiff !== 0) {
					return priorityDiff;
				}

				// 第三优先级：保持原有顺序（通过originalIndex）
				return 0;
			});
		}
	},
	onLoad() {
		this.loadMemos();
	},
	onShow() {
		this.loadMemos();
		// #ifdef APP-PLUS
		var icon = plus.nativeObj.View.getViewById("icon");
		if (icon) {
			setTimeout(function () {
				icon.show();
			}, 100)
		}
		// #endif
	},
	onReady() {
		// 监听来自"我的"页面的过滤事件
		uni.$on('filterMemos', (data) => {
			this.filterType = data.type;
			this.searchKeyword = ''; // 清空搜索关键词
		});
	},
	onUnload() {
		// 移除事件监听
		uni.$off('filterMemos');
	},
	methods: {
		// 搜索输入
		onSearchInput(e) {
			this.searchKeyword = e.detail.value;
		},

		// 清除搜索
		clearSearch() {
			this.searchKeyword = '';
		},
		
		// 清除过滤
		clearFilter() {
			this.filterType = 'all';
		},

		// 截取内容（限制50字）
		getTruncatedContent(content) {
			// 去除HTML标签
			const plainText = content.replace(/<[^>]*>/g, '');
			// 限制50个字符
			if (plainText.length > 100) {
				return plainText.substring(0, 100) + '...';
			}
			return plainText;
		},

		// 显示详情
		showDetail(index) {
			this.detailMemo = this.memos[index];
			this.showDetailModal = true;
		},

		// 关闭详情模态框
		closeDetailModal() {
			this.showDetailModal = false;
			this.detailMemo = {};
		},

		// 获取优先级文本
		getPriorityText(priority) {
			const priorityMap = {
				'low': '低',
				'medium': '中',
				'high': '高'
			};
			return priorityMap[priority] || '中';
		},

		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return '';
			// 数据库返回的时间已经是北京时间，直接格式化显示
			// 如果是 ISO 格式，去掉时区信息后解析
			const cleanTime = timeStr.replace('Z', '').replace(/\+\d{2}:\d{2}$/, '');
			const date = new Date(cleanTime);

			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hours = String(date.getHours()).padStart(2, '0');
			const minutes = String(date.getMinutes()).padStart(2, '0');
			const seconds = String(date.getSeconds()).padStart(2, '0');
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		},

		// 删除备忘录
		async deleteMemo(index) {
			const memo = this.memos[index];

			uni.showModal({
				title: '提示',
				content: '确定删除此备忘录吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							uni.showLoading({ title: '删除中...' });

							const apiRes = await memoAPI.delete(memo.id);

							uni.hideLoading();

							if (apiRes.code === 200) {
								this.loadMemos(); // 重新加载列表

								uni.showToast({
									title: '已删除',
									icon: 'success',
									duration: 1500
								});
							}
						} catch (error) {
							uni.hideLoading();
							console.error('删除失败:', error);
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},

		// 标记为完成
		async completeMemo(index) {
			const memo = this.memos[index];

			try {
				const res = await memoAPI.complete(memo.id);

				if (res.code === 200) {
					this.loadMemos(); // 重新加载列表

					uni.showToast({
						title: '已标记为完成',
						icon: 'success',
						duration: 1500
					});
				} else {
					uni.showToast({
						title: res.message || '操作失败',
						icon: 'none',
						duration: 2000
					});
				}
			} catch (error) {
				console.error('标记完成失败:', error);
				uni.showToast({
					title: '操作失败',
					icon: 'none'
				});
			}
		},

		// 打开编辑模态框
		editMemo(index) {
			const memo = this.memos[index];
			this.editingIndex = index;
			this.editMemoId = memo.id;
			this.editContent = memo.content;
			this.editPriority = memo.priority || 'medium';

			// 格式化时间
			const remindTime = memo.remind_time;
			if (remindTime) {
				// 处理数据库返回的时间格式 - 去掉时区信息直接解析为本地时间
				const cleanTime = remindTime.replace('Z', '').replace(/\+\d{2}:\d{2}$/, '');
				const date = new Date(cleanTime);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');

				this.editDateTime = `${year}-${month}-${day} ${hours}:${minutes}:00`;
			}
			this.showEditModal = true;
		},

		// 关闭编辑模态框
		closeEditModal() {
			this.showEditModal = false;
			this.editingIndex = -1;
			this.editMemoId = null;
			this.editContent = '';
		},

		// 保存编辑
		async saveEdit() {
			if (this.editContent.trim() === '') {
				uni.showToast({
					title: '内容不能为空',
					icon: 'none'
				});
				return;
			}

			if (!this.editDateTime) {
				uni.showToast({
					title: '请选择创建时间',
					icon: 'none'
				});
				return;
			}

			try {
				uni.showLoading({ title: '保存中...' });

				const res = await memoAPI.update(this.editMemoId, {
					content: this.editContent,
					remindTime: this.editDateTime,
					priority: this.editPriority
				});

				uni.hideLoading();

				if (res.code === 200) {
					this.closeEditModal();
					this.loadMemos(); // 重新加载列表

					uni.showToast({
						title: '已保存',
						icon: 'success',
						duration: 1500
					});
				} else {
					uni.showToast({
						title: res.message || '保存失败',
						icon: 'none',
						duration: 2000
					});
				}
			} catch (error) {
				uni.hideLoading();
				console.error('保存失败:', error);
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				});
			}
		},

		// 从 API 加载备忘录
		async loadMemos() {
			try {
				const res = await memoAPI.getList();

				if (res.code === 200) {
					// 数据库字段映射
					this.memos = res.data.map(memo => ({
						...memo,
						remindTime: memo.remind_time,
						createTime: memo.created_at
					}));
				} else {
					this.memos = [];
					console.error('加载失败:', res.message);
				}
			} catch (error) {
				console.error('加载备忘录失败:', error);
				this.memos = [];
			}
		},

		// 保存到本地存储（已废弃）
		saveMemos() {
			// 不再需要保存到本地存储
			console.log('数据已通过API保存到数据库');
		}
	}
}
</script>

<style>
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
	background-color: #f8f9fa;
	box-sizing: border-box;
}

/* 搜索栏 */
.search-bar {
	background-color: #fff;
	padding: 20rpx;
	border-bottom: 1rpx solid #e0e0e0;
	box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
}

.search-input-wrapper {
	display: flex;
	align-items: center;
	background-color: #f5f5f5;
	border-radius: 20rpx;
	padding: 12rpx 20rpx;
	height: 70rpx;
	box-sizing: border-box;
}

.search-icon {
	font-size: 28rpx;
	margin-right: 10rpx;
	color: #999;
	flex-shrink: 0;
}

.search-input {
	flex: 1;
	font-size: 28rpx;
	color: #333;
	background-color: transparent;
	border: none;
	outline: none;
	height: 100%;
	line-height: normal;
}

.clear-icon {
	font-size: 32rpx;
	color: #999;
	margin-left: 10rpx;
	padding: 0 8rpx;
	cursor: pointer;
	flex-shrink: 0;
}

.filter-tag {
	display: inline-flex;
	align-items: center;
	background-color: #e6f2ff;
	color: #007aff;
	padding: 6rpx 14rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
	margin-top: 12rpx;
}

.filter-text {
	margin-right: 8rpx;
}

.filter-clear {
	font-size: 28rpx;
	font-weight: bold;
	cursor: pointer;
}

/* 备忘录列表 */
.memo-list {
	flex: 1;
	padding: 20rpx;
	overflow-y: auto;
}

.memo-item {
	background-color: #fff;
	padding: 20rpx;
	margin-bottom: 12rpx;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
}

.memo-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 12rpx;
	padding-bottom: 12rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.header-left {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
	flex: 1;
}

.memo-time {
	font-size: 24rpx;
	color: #999;
}

/* 优先级徽章 */
.priority-badge {
	display: inline-block;
	padding: 4rpx 12rpx;
	border-radius: 12rpx;
	font-size: 20rpx;
	align-self: flex-start;
}

.priority-badge.priority-low {
	background-color: #e8f9ed;
	color: #34c759;
}

.priority-badge.priority-medium {
	background-color: #fff8e8;
	color: #ff9500;
}

.priority-badge.priority-high {
	background-color: #ffe8e8;
	color: #ff3b30;
}

.badge-text {
	font-weight: 500;
}

.memo-actions {
	display: flex;
	gap: 20rpx;
}

.action-btn {
	font-size: 24rpx;
	padding: 6rpx 12rpx;
	border-radius: 6rpx;
}

.detail {
	color: #8e44ad;
	background-color: #f4ecf7;
}

.edit {
	color: #007aff;
	background-color: #f0f7ff;
}

.delete {
	color: #ff3b30;
	background-color: #fff0f0;
}

.complete {
	color: #34c759;
	background-color: #f0fff4;
}

.status-badge {
	font-size: 24rpx;
	color: #34c759;
	background-color: #f0fff4;
	padding: 6rpx 12rpx;
	border-radius: 6rpx;
}

.memo-content-wrapper {
	margin: 12rpx 0;
}

.memo-content-text {
	font-size: 28rpx;
	color: #333;
	line-height: 40rpx;
	word-wrap: break-word;
	white-space: pre-wrap;
}

.memo-status {
	margin-top: 10rpx;
}

.status-text {
	font-size: 20rpx;
	color: #ff9500;
	background-color: #fffbf0;
	padding: 4rpx 8rpx;
	border-radius: 4rpx;
	display: inline-block;
}

.status-text.pending {
	color: #007aff;
	background-color: #f0f7ff;
}

/* 空状态 */
.empty-state {
	flex: 1;
	display: flex;
	justify-content: center;
	align-items: center;
}

.empty-text {
	font-size: 28rpx;
	color: #ccc;
}

/* 模态框 */
.modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: flex-end;
	z-index: 999;
}

.modal-content {
	background-color: #fff;
	width: 100%;
	max-width: 100%;
	padding: 30rpx 20rpx;
	border-radius: 20rpx 20rpx 0 0;
	animation: slideUp 0.3s ease-out;
	max-height: 80vh;
	overflow-y: auto;
	overflow-x: hidden;
	box-sizing: border-box;
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}

	to {
		transform: translateY(0);
	}
}

.modal-input {
	width: 100%;
	max-width: 100%;
	min-height: 500rpx;
	padding: 15rpx;
	border: 1rpx solid #e0e0e0;
	border-radius: 8rpx;
	font-size: 28rpx;
	line-height: 40rpx;
	resize: none;
	background-color: #fafafa;
	margin-bottom: 20rpx;
	box-sizing: border-box;
	word-wrap: break-word;
	word-break: break-all;
}

/* 优先级选择区域 */
.priority-section {
	margin: 15rpx 0;
	width: 100%;
	max-width: 100%;
	box-sizing: border-box;
}

.priority-tabs {
	display: flex;
	gap: 12rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	padding: 4rpx;
	width: 100%;
	box-sizing: border-box;
}

.priority-tab {
	flex: 1;
	text-align: center;
	padding: 10rpx 0;
	border-radius: 6rpx;
	transition: all 0.3s ease;
	cursor: pointer;
}

.priority-tab.active {
	background-color: #fff;
	box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.priority-tab.active.priority-low,
.priority-tab:nth-child(1).active {
	background-color: #34c759;
}

.priority-tab.active.priority-medium,
.priority-tab:nth-child(2).active {
	background-color: #ff9500;
}

.priority-tab.active.priority-high,
.priority-tab:nth-child(3).active {
	background-color: #ff3b30;
}

.priority-text {
	font-size: 26rpx;
	color: #666;
}

.priority-tab.active .priority-text {
	color: #fff;
	font-weight: 500;
}

.time-picker-group {
	display: flex;
	align-items: center;
	gap: 10rpx;
	margin: 15rpx 0;
	flex-wrap: wrap;
	width: 100%;
	max-width: 100%;
	box-sizing: border-box;
}

.time-label {
	font-size: 24rpx;
	color: #666;
	white-space: nowrap;
}

.modal-buttons {
	display: flex;
	gap: 15rpx;
	margin-top: 20rpx;
	width: 100%;
	max-width: 100%;
	box-sizing: border-box;
}

.btn {
	flex: 1;
	padding: 12rpx 20rpx;
	border-radius: 8rpx;
	font-size: 28rpx;
	font-weight: 500;
	border: none;
}

.btn-primary {
	background-color: #007aff;
	color: #fff;
}

.btn-secondary {
	background-color: #f0f0f0;
	color: #666;
}

/* 详情模态框 */
.detail-modal {
	max-height: 70vh;
}

.detail-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid #e0e0e0;
	margin-bottom: 20rpx;
}

.detail-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.close-btn {
	font-size: 40rpx;
	color: #999;
	cursor: pointer;
	padding: 0 10rpx;
}

.detail-body {
	overflow-y: auto;
	max-height: 55vh;
}

.detail-info {
	display: flex;
	align-items: flex-start;
	margin-bottom: 15rpx;
	padding: 10rpx;
	background-color: #f9f9f9;
	border-radius: 8rpx;
}

.detail-label {
	font-size: 26rpx;
	color: #666;
	font-weight: 500;
	min-width: 140rpx;
	flex-shrink: 0;
}

.detail-value {
	font-size: 26rpx;
	color: #333;
	flex: 1;
	word-wrap: break-word;
}

.detail-content-section {
	margin-top: 20rpx;
	padding: 15rpx;
	background-color: #f9f9f9;
	border-radius: 8rpx;
}

.detail-content-section .detail-label {
	display: block;
	margin-bottom: 10rpx;
}

.detail-content {
	font-size: 28rpx;
	color: #333;
	line-height: 42rpx;
	word-wrap: break-word;
	white-space: pre-wrap;
}
</style>
